<template>
  <div class="container dark-theme" @click="closeMenuOnClickOutside">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <!-- <router-link to="/home">首页</router-link> -->
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="notification">
          <router-link to="/notice">
            <i class="el-icon-message"></i>
          </router-link>
        </div>
        <div class="avatar-box">
          <img
            :src="user.icon"
            class="avatar"
            alt="用户头像"
            @click.stop="toggleMenu"
          />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>

    <!-- 信用数据大屏区域 -->
    <div class="screen">
      <div class="top-cards">
        <div class="card">全国信用人数<br /><span>{{ stats.people }}</span></div>
        <div class="card">良好信用用户<br /><span>{{ stats.good }}</span></div>
        <div class="card">守约率<br /><span>{{ stats.promiseRate }}%</span></div>
      </div>

      <div class="middle-charts">
        <div ref="trendChart" class="chart-box"></div>
        <div ref="mapChart" class="chart-box"></div>
        <div ref="pieChart" class="chart-box"></div>
      </div>

      <div class="bottom-charts">
        <div ref="boxChart" class="chart-box"></div>
        <div ref="barChart" class="chart-box"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from "axios";
// Axios interceptors 保持不变
axios.interceptors.request.use(
  (config) => {
    const token = window.sessionStorage.getItem('token');
    if (token) config.headers.Authorization = `${token}`;
    return config;
  },
  (error) => Promise.reject(error)
);

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      sessionStorage.removeItem('token');
      location.href = '/login-code';
    }
    return Promise.reject(error);
  }
);

export default {
  name: 'Home',
  data() {
    return {
      user: {},
      isMenuOpen: false,
      imageBaseUrl: 'http://localhost:8089',

      stats: {
        people: '3,024,944',
        good: '2,324,230',
        promiseRate: 96.7,
      },
      charts: {},
    };
  },
  created() {
    this.queryUser();
  },
  mounted() {
    this.initCharts();
  },
  methods: {
    queryUser() {
      axios.get('/users/user/me', {
        headers: { Authorization: `${localStorage.getItem('token')}` }
      }).then(({ data }) => {
        if (data.success && data.data) {
          this.user = data.data;
          if (this.user.icon && !this.user.icon.startsWith('http')) {
            this.user.icon = `${this.imageBaseUrl}${this.user.icon}`;
          }
          this.queryUserInfo();
        }
      });
    },
    queryUserInfo() {
      axios.get(`/users/user/basic`)
        .then(({ data }) => {
          this.info = data || { introduce: '' };
          sessionStorage.setItem('userInfo', JSON.stringify(data));
        })
        .catch(err => this.$message.error(err.message));
    },
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    logout() {
      sessionStorage.removeItem('token');
      this.$router.push('/login-code');
    },
    initCharts() {
      const option1 = {
        title: { text: '信用趋势', textStyle: { color: '#fff' } },
        xAxis: { data: ['1月','2月','3月','4月','5月'], axisLine: { lineStyle: { color: '#fff' } } },
        yAxis: { axisLine: { lineStyle: { color: '#fff' } } },
        series: [{ type: 'line', data: [320, 400, 310, 500, 420], lineStyle: { color: '#4fc3f7' } }],
      };
      const option2 = {
        title: { text: '信用等级分布', left: 'center', textStyle: { color: '#fff' } },
        series: [
          {
            type: 'pie',
            radius: '60%',
            data: [
              { value: 58, name: '优' },
              { value: 26, name: '良' },
              { value: 10, name: '中' },
              { value: 6, name: '差' },
            ],
            label: { color: '#fff' },
          },
        ],
      };
      const option3 = {
        title: { text: '信用行为类型柱状图', textStyle: { color: '#fff' } },
        xAxis: {
          type: 'category',
          data: ['生活', '商业', '公益', '消费'],
          axisLine: { lineStyle: { color: '#fff' } },
        },
        yAxis: { type: 'value', axisLine: { lineStyle: { color: '#fff' } } },
        series: [
          {
            data: [1200, 800, 950, 1000],
            type: 'bar',
            itemStyle: { color: '#29b6f6' },
          },
        ],
      };
      const chartRefs = ['trendChart', 'mapChart', 'pieChart', 'boxChart', 'barChart'];
      chartRefs.forEach((ref, i) => {
        const chart = echarts.init(this.$refs[ref]);
        if (ref === 'trendChart') chart.setOption(option1);
        else if (ref === 'pieChart') chart.setOption(option2);
        else chart.setOption(option3); // 示例：其余使用相同结构
        this.charts[ref] = chart;
      });
    },
  },
};
</script>

<style scoped>
.container.dark-theme {
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  min-height: 100vh;
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}
.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
}
.header .logo {
  font-size: 20px;
  color: #4fc3f7;
}
.header .nav a {
  margin: 0 10px;
  color: #fff;
  text-decoration: none;
}
.user-menu {
  position: relative;
  display: flex;
  align-items: center;
}
.notification {
  margin-right: 10px;
}
.notification a {
  color: #fff;
  text-decoration: none;
}
.notification i {
  font-size: 24px;
  color: #4fc3f7;
}
.notification i:hover {
  color: #2196f3;
}
.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #4fc3f7;
}
.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  background: #002d52;
  border: 1px solid #4fc3f7;
  border-radius: 4px;
  z-index: 10;
}
.menu-item {
  padding: 10px;
  color: #fff;
  cursor: pointer;
}
.menu-item:hover {
  background: #014b75;
}
.screen {
  padding: 20px;
}
.top-cards {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}
.top-cards .card {
  background: #003b64;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  font-size: 18px;
  width: 30%;
  box-shadow: 0 0 10px #29b6f6;
}
.top-cards .card span {
  font-size: 24px;
  display: block;
  margin-top: 10px;
  color: #4fc3f7;
}
.middle-charts, .bottom-charts {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
.chart-box {
  width: 30%;
  height: 300px;
  background: #012c4a;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 0 10px #1e88e5;
}
</style>
